/**
 * Created by spatra on 14-12-2.
 */


/**
 * 前端使用AngularJS构建的Web App应用的统一入口
 */
define(['angular', 'projectJS/ng-require', 'personalJS/ng-require', 'commonJS/ng-require','globalNotificationJS/ng-require', 'angularUIRouter','angularAnimate','angularToasty'],
  function(angular, projectModule, personalModule, commonModule, globalNotificationModule){

  var app = angular.module('TeamMindmap', [projectModule, personalModule, commonModule, globalNotificationModule, 'ui.router','ngAnimate','toasty']);

  app.constant('baseUrl', 'ngApp/');

  app.run(['$rootScope', 'MainTopNavInitService', 'LoginStatusService', 'GlobalNotificationService',
    function($rootScope, MainTopNavInitService, LoginStatusService, GlobalNotificationService){
      LoginStatusService.init();
      $rootScope.functionNavItems = MainTopNavInitService.getFunctionNavItems();

      //让标题随着页面改变
      $rootScope.$on('$stateChangeSuccess', function (event, toState) {
        $rootScope.title = toState.title || 'TeamMindmap';
      });

      GlobalNotificationService.init($rootScope); //在根作用域下初始化全局通知
   }]);

  app.config(['$httpProvider', '$stateProvider', '$urlRouterProvider', 'baseUrl',
    function($httpProvider, $stateProvider, $urlRouterProvider, baseUrl){
      //设置CSRF防护TOKEN
      $httpProvider.defaults.headers.common['X-CSRF-TOKEN'] = $('meta[name=csrf-token]').attr('content');


      $urlRouterProvider.otherwise('project/list');

      //设置UI Router规则
      $stateProvider
        .state('project',{
          url: '/project',
          views: {
            '': {
              templateUrl: 'ngApp/common/tpls/layout-ng.html'
            },
            'notification@project': {
              templateUrl: 'ngApp/globalNotification/tpls/notification-template.html'
            }
          },
          abstract: true
        })
        .state('project.list', {
          url: '/list',
          title: '项目列表',
          views: {
            'main@project': {

              templateUrl: baseUrl + 'project/tpls/project-list.html',
              controller: 'ProjectListController'
            }
          },
          resolve: {
            projectList: ['ProjectService', function(ProjectService) {
              return ProjectService.getAllProjects();
            }]
          }

        })
        .state('project.creating', {
          url: '/creating',
          title: '新建项目',
          views: {
            'main@project': {
              templateUrl: baseUrl + 'project/tpls/project-creating.html',
              controller: "ProjectCreatingController"
            }
          },
          resolve: {
            roleList: ['RoleService', function(RoleService){
              return RoleService.accessor.get()
                .then(function(resp){ return resp.data; },
                  function(data){ alert('用户角色加载出错'); console.error(data); }
              );
            }],
            currUser: ['$http', function($http){
              return $http.get('/api/personal/info')
                .then(function(resp){ return resp.data },
                  function(data) { alert('个人信息加载出错'); console.error(data); }
              )
            }]
          }
        })
        .state('project.show', {
          url: '/:projectId',
          resolve:{
            currentProjectId: ['$stateParams', function($stateParams){
              return $stateParams.projectId;
            }],
            currentProjectInfo: ['currentProjectId', 'ProjectService', function(currentProjectId, ProjectService){
              return ProjectService.accessor.show(currentProjectId)
                .then(function(resp){ return resp.data; }, function(resp){
                  console.error(resp.data);
                  alert('加载项目信息出错!');
                });
            }]
          },
          views: {
            'main@project': {
              templateUrl: baseUrl + 'project/tpls/project-workpanel.html'
            },
            'sidebar@project.show': {
              template: '<project-sidebar></project-sidebar>'
            }
          },
          abstract: true
        })
        .state('project.show.desktop', {
          url: '/desktop',
          title: '项目工作台',
          resolve: {
            taskSet: ['$stateParams', 'TaskService', function($stateParams, TaskService){
              TaskService.accessor['setParentResourceId']($stateParams);
              //@workaround暂时只获取第一层任务
              return TaskService.accessor.get()
                .then(function(resp){  return resp.data;},
                    function(data){ alert('加载任务信息出错'); console.log(data);})

            }]
          },
          views: {
            'main-content@project.show': {
              templateUrl: baseUrl + 'project/tpls/project-desktop.html',
              controller: 'ProjectDesktopController'

            }
          }
        })
        .state('project.show.desktop.taskInfo', {
          url: '/taskInfo/:taskId',
          title: '项目具体任务',

          views: {
            'info@project.show.desktop': {
              template: '<task-info></task-info>'
            }
          }
        })
        .state('project.show.task', {
          url: '/task',
          title: '项目任务列表',
          resolve: {
            taskStatusSet: ['TaskStatusService', function(TaskStatusService){
              return TaskStatusService.getStatusSet();
            }],

            taskSet: ['$stateParams', 'TaskService', 'TaskStatusService', function($stateParams, TaskService, TaskStatusService){

              return TaskStatusService.accessor.get()
                .then(function(resp){
                  return TaskService.getTaskSetWithPagination($stateParams, resp.data);
                },function(data){
                  console.log(data);
                })
            }],
            taskConditions: ['TaskPriorityService', 'TaskService', function(TaskPriorityService, TaskService){
              return TaskPriorityService.accessor.get()
                .then(function(resp){
                  return {
                    'priority_id': TaskService.convertToCondItems(resp.data, 'id', 'label')
                    //'datetimes': [
                    //  {cond: 'month', label: '一个月以来'}, {cond: 'week', label: '一周以内'}, {cond: 'twodays', label: '两天之内'}, {cond: 'today', label: '今日之内'}
                    //]
                  };
                }, function(resp){
                  alert('加载添加任务条件信息失败');
                  console.error(resp.data);
                });
            }]
          },
          views: {
            'main-content@project.show': {
              templateUrl: baseUrl + 'project/tpls/project-task.html',
              controller: 'TaskController'
            }
          }
        })
        .state('project.show.task.info', {
          url: '/:taskId',
          title: '项目具体任务',
          views: {
            'info@project.show.task': {
              template: '<task-info></task-info>'
            }
          }
        })
        .state('project.show.discussion', {
          url: '/discussion',
          title: '讨论',
          views: {
            'main-content@project.show': {
              templateUrl: baseUrl + 'project/tpls/discussion-list.html',
              resolve: {
                discussionList: ['$stateParams', 'DiscussionService', function($stateParams, DiscussionService){
                  DiscussionService.accessor['setParentResourceId']($stateParams);

                  return DiscussionService.accessor.get({
                    params:{
                      per_page: 10,
                      page: 1,
                      option: {
                        open: 1,
                        user: 1
                      }

                    }
                  })
                    .then(function(resp){ return resp.data; },
                      function(resp){
                        console.error(resp.data);
                        alert('加载讨论列表出错');
                      }
                  );
                }],
                'discussionFilterConditions': ['BackendFilterService', function(BackendFilterService){
                  return BackendFilterService.getMethods('projectDiscussion')
                    .then(function(resp){ return resp.data; },
                      function(resp){
                        console.error(resp.data);
                        alert('加载过滤条件出错');
                      });
                }]
              },
              controller: 'DiscussionListController'
            }
          }
        })
        .state('project.show.discussion.creating', {
          url: '/creating',
          title: '发起新的讨论',
          views:{
            'main-content@project.show':{
              templateUrl: baseUrl + 'project/tpls/discussion-creating.html',
              resolve: {
                'userList': ['$stateParams', 'ProjectService', function($stateParams, ProjectService){
                  return ProjectService.getCreaterAndMembers( $stateParams.projectId );
                }]
              },
              controller: 'DiscussionCreatingController'
            }
          }
        })
        .state('project.show.discussion.info', {
          url: '/:discussionId',
          title: '讨论查看',
          views: {
            'main-content@project.show': {
              templateUrl: baseUrl + 'project/tpls/discussion-info.html',
              resolve: {
                'currentDiscussion': ['$stateParams', 'DiscussionService', function($stateParams, DiscussionService){
                  DiscussionService.accessor['setParentResourceId']($stateParams);

                  return DiscussionService.accessor.show($stateParams['discussionId'])
                    .then(function(resp){ return resp.data; },
                    function(resp){
                      console.error(resp.data);
                      alert('加载讨论出错!');
                    }
                  );
                }],
                'commentList': ['$stateParams', 'CommentService', function($stateParams, CommentService){
                  CommentService.accessor['setParentResourceId']($stateParams);

                  return CommentService.accessor.get({
                    params: {
                      per_page: 10,
                      page: 1
                    }
                  })
                    .then(function(resp){ return resp.data; },
                    function(resp){
                      console.error(resp.data);
                      alert('加载评论出错!');
                    });

                }]
              },
              controller: 'DiscussionInfoController'
            }
          }
        })
        .state('project.show.member',{
          url: '/member',
          title: '项目成员',
          views: {
            'main-content@project.show': {
              templateUrl: baseUrl + 'project/tpls/project-member.html',
              resolve: {
                conditions: ['roleInfo', function(roleInfo){
                  var rtn = {'role': []};

                  rtn['role'].push({cond: 0, label: '所有人'});

                  roleInfo.forEach(function(item){
                    rtn['role'].push({
                      'cond': item.id,
                      'label': item.label
                    });
                  });

                  return rtn;
                }]
              },
              controller: 'ProjectMemberController'
            }
          },
          resolve: {
            roleInfo: ['RoleService', function(RoleService){
              return RoleService.accessor.get()
                .then(function(resp){
                  return resp.data;
                }, function(resp){
                  alert('Error!');
                  console.error(resp.data);
                });
            }]
          }
        })
        .state('project.show.member.creating', {
          url: '/creating',
          views: {
            'main-content@project.show': {
              templateUrl: baseUrl + 'project/tpls/project-member-creating.html',
              controller: 'ProjectMemberCreatingController'
            }
          }
        })
        .state('project.show.setting', {
          url: '/setting',
          title: '项目设置',
          views: {
            'main-content@project.show': {
              templateUrl: baseUrl + 'project/tpls/project-setting.html',
              resolve: {
              },
              controller: 'ProjectSettingController'
            }
          }
        })
        .state('project.show.sharing', {
          url: '/sharing',
          views: {
            'main-content@project.show': {
              templateUrl: baseUrl + 'project/tpls/sharing-content.html'
            },
            'third-nav@project.show.sharing': {
              template: '<module-third-nav nav-items="navItems" parent-state-name="project.show.sharing"></module-third-nav>',
              controller: ['$scope', function($scope){
                $scope.navItems = [
                  {label: '分享列表', uiSref: 'project.show.sharing.list'},
                  {label: '创建分享', uiSref: 'project.show.sharing.creating'}
                ];
              }]
            }
         },
          abstract: true
        })
        .state('project.show.sharing.list', {
          url: '/list',
          title: '分享墙',
          views: {
            'sharing-content@project.show.sharing': {
              templateUrl: baseUrl + 'project/tpls/sharing-list.html',
              resolve: {
                'sharingList': ['$stateParams', 'ProjectSharingService',
                  function($stateParams, ProjectSharingService){

                    return ProjectSharingService.getOnStartPaginationConf($stateParams)
                      .then(function(resp){
                        return resp.data;
                      }, function(resp){
                        console.error(resp.data);
                        alert('加载分享列表失败');
                      });
                }]
              },
              controller: 'ProjectSharingListController'
            }
          }
        })
        .state('project.show.sharing.info', {
          url: '/info/:sharingId',
          title: '分享的详细信息',
          views: {
            'sharing-content@project.show.sharing': {
              templateUrl: baseUrl + 'project/tpls/sharing-info.html',
              resolve: {
                'sharingInfo': ['$stateParams', 'ProjectSharingService',
                    function($stateParams, ProjectSharingService){
                      ProjectSharingService.accessor['setParentResourceId']($stateParams);

                      return ProjectSharingService.accessor.show($stateParams['sharingId'])
                        .then(function(resp){
                          return resp.data;
                        }, function(resp){
                          console.log(resp);
                        })

                    }]
              },
              controller: 'ProjectSharingInfoController'
            },
            'third-nav@project.show.sharing': {
              template: ''
            }
          }
        })
        .state('project.show.sharing.creating', {
          url: '/creating',
          title: '创建分享',
          views: {
            'sharing-content@project.show.sharing': {
              templateUrl: baseUrl + 'project/tpls/sharing-creating.html',
              resolve: {
                'projectTags': ['$stateParams', 'ProjectTagService', function($stateParams, ProjectTagService){
                  ProjectTagService.accessor['setParentResourceId']($stateParams);

                  return ProjectTagService.accessor.get()
                    .then(function(resp){
                      return resp.data;
                    }, function(resp){
                      console.error(resp);
                      alert('加载项目标签出错');
                    })
                }]
              },
              controller: 'ProjectSharingCreatingController'
            }

          }
        })
        .state('personal', {
          url: '/personal',
          views: {
            '': {
              templateUrl: 'ngApp/common/tpls/layout-ng.html'
            },
            'notification@personal': {
              templateUrl: 'ngApp/globalNotification/tpls/notification-template.html'
            },
            'main@personal': {
              templateUrl: 'ngApp/personal/tpls/personal-template.html'
            },
            'second-nav@personal': {
              template: '<personal-second-nav nav-items="navItems">{{ navItems }}</personal-second-nav>',
              controller: ['$scope', function($scope){
                //用户初始化个人模块的左侧二级导航栏
                $scope.navItems = [
                  {label: '资料', uiSref:'personal.information.setting'},
                  {label: '通知', uiSref:'personal.notification'},
                  {label: '私信', uiSref:'personal.message.list'}
                ];
              }]
            }
          },
          abstract: true
        })
        .state('personal.information',{
          url: '/information',
          views: {
            'third-nav@personal': {
              template: '<third-nav base-state="baseState" nav-items="navItems"></third-nav>',
              controller: ['$scope', function($scope){
                //初始化三级导航栏
                $scope.baseState = 'personal.information';
                $scope.navItems = [
                  {label: '个人设置', state: 'setting'},
                  {label: '修改密码', state: 'password'}
                ];
              }]
            }
          }

        })

        .state('personal.information.setting',{
          url: '/setting',
          title: '个人设置',
          views: {
            'third-title@personal': {
              template: '<div class="third-title"><h3>用户设置</h3><hr/></div>'
            },
            'main-content@personal': {
              templateUrl: baseUrl + 'personal/tpls/info-setting.html',
              controller: 'PersonalSettingController'
            }
          },
          resolve:{
            'userInfo': ['LoginStatusService', function(LoginStatusService){
              return LoginStatusService.get('personalInfo');
            }]
          }
        })
        .state('personal.information.password',{
          url: '/password',
          title: '修改密码',
          views: {
            'third-title@personal': {
              template: '<div class="third-title"><h3>密码修改</h3><hr/></div>'
            },
            'main-content@personal': {
              templateUrl: baseUrl + 'personal/tpls/password-setting.html',
              controller: 'PasswordEditController'
            }
          }
        }).
        state('personal.notification',{
          url: '/notification',
          views: {
            'third-title@personal': {
              template: '<div class="third-title"><h3>我的通知</h3><hr/></div>'
            },
            'main-content@personal': {
              templateUrl: baseUrl + 'personalNotification/tpls/notification-index.html',
              resolve: {
                projectList: ['ProjectService', function(ProjectService) {
                  return ProjectService.getAllProjects();
                }],
                notificationList: ['NotificationService', function(NotificationService){
                  return NotificationService.accessor.get({
                    params: {
                      per_page: 10,
                      page: 1,
                      project_id: null,  //null:全部项目
                      read: 0    //1:read  0:unread

                    }
                  })
                    .then(function(resp){
                      return resp.data;
                    },
                    function(resp){ alert('通知列表加载失败');  console.error(resp.data); });
                }],
                'typeLabelSet': ['NotificationTypeService', function(NotificationTypeService){
                  return NotificationTypeService.getTypeLabelSet();
                }]
              },
              controller: 'NotificationController'
            }
          }
        }).
        state('personal.message',{
          url: '/message',
          views: {
            'third-nav@personal': {
              template: '<third-nav base-state="baseState" nav-items="navItems"></third-nav>',
              controller: ['$scope', function ($scope) {
                //初始化三级导航栏
                $scope.baseState = 'personal.message';
                $scope.navItems = [
                  {label: '查看私信', state: 'list'},
                  {label: '编写私信', state: 'creating'}
                ];
              }]
            }
          }
        })
        .state('personal.message.list',{
          url: '/list',
          views: {
            'third-title@personal': {
              template: '<div class="third-title"><h3>查看私信</h3><hr/></div>'
            },
            'main-content@personal': {
              templateUrl: baseUrl + 'personalMessage/tpls/message-list.html',
              resolve: {
                messageList: ['MessageService', function(MessageService){
                  return MessageService.accessor.get({
                    params: {
                      per_page: 10,
                      page: 1,
                      option: 'received'
                    }
                  })
                    .then(function(resp){
                      return resp.data;
                    }, function(resp){
                      alert('私信列表加载出错!');
                      console.error(resp.data);
                    });
                }]
              },
              controller: 'MessageListController'
            }
          }
        })
        .state('personal.message.list.show',{
          url: '/show',
          views: {
            'third-title@personal': {
              template: ''
            },
            'third-nav@personal': {
              template: ''
            },
            'main-content@personal': {
              templateUrl: baseUrl + 'personalMessage/tpls/message-show.html',
              resolve: {
                currentMessageInfo: ['MessageService', function(MessageService){
                  return MessageService.currentMessageInfo;
                }]
              },
              controller: 'MessageShowController'
            }
          }
        })
        .state('personal.message.creating',{
          url: '/creating',
          views: {
            'third-title@personal': {
              template: '<div class="third-title"><h3>编写私信</h3><hr/></div>'
            },
            'main-content@personal': {
              templateUrl: baseUrl + 'personalMessage/tpls/message-creating.html',
              resolve: {
                projectList: ['ProjectService', function(ProjectService){
                  return ProjectService.getAllProjects();
                }]
              },
              controller: 'MessageCreatingController'
            }
          }

        })
      ;
    }]);

  return app;

});